package speedball.sound;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {
    public static void main(String[] args) {
        new Main();
    }
    WavePanel panel = new WavePanel();
    public Main() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        add(panel);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        new Thread(new Runnable() {
            public void run() {
                try {
                    while (true) {
                        Thread.sleep(100);
                        panel.repaint();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    class WavePanel extends JPanel {
        final int bufWidth = 400, bufHeight = 200;
        final int len = 100;
        final int lifeLine = (int) (bufWidth * 0.75);
        final int midHeight = bufHeight >> 1;
        final int perw = lifeLine / len;
        final BufferedImage buf = new BufferedImage(bufWidth, bufHeight,
                BufferedImage.TYPE_INT_ARGB);
        final int a[] = new int[len];
        final Random random = new Random();
        public int ai = 0;
        public WavePanel() {
            setPreferredSize(new Dimension(bufWidth, bufHeight));
        }
        @Override
        protected void paintComponent(Graphics g) {
            ai = (ai + 1) % len;
            a[ai] = random.nextInt(100);
            Graphics gg = buf.getGraphics();
            gg.clearRect(0, 0, buf.getWidth(), buf.getHeight());
            gg.setColor(Color.RED);
            for (int i = 0; i < len; i++) {
                int j = (ai - i + len) % len;
                int leftSpace = perw / 3;
                int x = lifeLine - i * perw;
                int y = midHeight - (a[j] >> 1);
                int w = (int) (0.6 * perw), h = a[j];
                gg.fillRect(x - leftSpace, y, w, h);
            }
            gg.setColor(Color.CYAN);
            gg.drawLine(lifeLine, 0, lifeLine, bufHeight - 1);
            g.drawImage(buf, 0, 0, null);
        }
    }
}
